package com.example.jiwhsgs;

import static android.content.ContentValues.TAG;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ZCactivity extends Activity {
    public class ZCData {
        public String name;
        public String s_name_1 = "";
        public String s_name_2 = "";
        public String s_name_3 = "";
        public String skill_1 = "";
        public String skill_2 = "";
        public String skill_3 = "";
        public boolean is_selected = false;
    }

    public class TextViewButtonPair {
        private Button button;
        private boolean isSelected;

        public TextViewButtonPair(Button button) {
            this.button = button;
            this.isSelected = false;
        }

        public Button getButton() {
            return button;
        }

        public boolean isSelected() {
            return isSelected;
        }

        public void setSelected(boolean selected) {
            isSelected = selected;
        }
    }

    private List<TextViewButtonPair> buttonsList = new ArrayList<>();
    private List<LinearLayout> linearLayoutList = new ArrayList<>();
    private SQLiteDatabase myDatabase;
    private TextView showSkill;
    private int which;
    private boolean isReplaceEnabled = false; // 新增标志
    private int selectedLinearLayoutCount = 0; // 记录已选择的 LinearLayout 数量
    private Button confirmButton; // 新增成员变量来保存确认按钮的引用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zc);
        which = 0;

        myDatabase = openOrCreateDatabase("sgsdb.db", MODE_PRIVATE, null);
        List<ZCData> zc_list = getZCData();

        // 打印 zclist 到日志
        //logZCData(zc_list);

        showSkill = findViewById(R.id.selectedSkill);
        List<Integer> indices = new ArrayList<>();
        for (int i = 0; i < zc_list.size(); i++) {
            indices.add(i);
        }

        Collections.shuffle(indices); // 乱序 zc_list

        LinearLayout topContainer = findViewById(R.id.topContainer);
        for (int i = 0; i < 3; i++) {
            ZCData zcData = zc_list.get(indices.get(i));
            zc_list.get(indices.get(i)).is_selected = true;
            createLinearlayout(zcData, topContainer);
        }

        setupButtons(zc_list, indices, topContainer);
    }

    private void logZCData(List<ZCData> zc_list) {
        for (ZCData zcData : zc_list) {
            Log.d(TAG, "jiwhblx " + zcData.name + " " + zcData.s_name_1 + " " + zcData.s_name_2 + " " + zcData.s_name_3 + zcData.is_selected);
        }
    }

    private void setupButtons(List<ZCData> zc_list, List<Integer> indices, LinearLayout topContainer) {
        Button xinsheng = findViewById(R.id.xinsheng);
        Button replace = findViewById(R.id.replace);
        LinearLayout buttonContainer = findViewById(R.id.buttonContainer);

        // 模拟点击 xinsheng 按钮两次
        simulateButtonClick(xinsheng);
        simulateButtonClick(xinsheng);

        xinsheng.setOnClickListener(v -> {
            int count = zc_list.size();
            while (zc_list.get(indices.get(which)).is_selected) {
                which = (which + 1) % count;
            }
            ZCData zcData = zc_list.get(indices.get(which));
            zc_list.get(indices.get(which)).is_selected = true;
            createLinearlayout(zcData, topContainer);
        });

        replace.setOnClickListener(v -> {
            toggleReplaceMode(buttonContainer, xinsheng, replace);
        });
    }

    private void toggleReplaceMode(LinearLayout buttonContainer, Button xinsheng, Button replace) {
        isReplaceEnabled = !isReplaceEnabled; // 切换 isReplaceEnabled 的值
        xinsheng.setVisibility(View.GONE); // 隐藏 xinsheng 按钮
        replace.setVisibility(View.GONE);

        confirmButton = createConfirmButton(buttonContainer, xinsheng, replace); // 将确认按钮的引用赋值给成员变量
        buttonContainer.addView(confirmButton);
    }

    private Button createConfirmButton(LinearLayout buttonContainer, Button xinsheng, Button replace) {
        Button confirmButton = new Button(this);
        confirmButton.setText("确定");
        confirmButton.setLayoutParams(new LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.MATCH_PARENT,
                1.0f // 权重
        ));
        confirmButton.setBackgroundResource(R.drawable.zc_button);
        confirmButton.setGravity(Gravity.CENTER);
        confirmButton.setTextColor(ContextCompat.getColor(this, R.color.black));
        confirmButton.setTextSize(20);
        confirmButton.setTypeface(null, Typeface.BOLD);
        confirmButton.setPadding(4, 0, 4, 0); // 设置左右间距

        TextView textView = findViewById(R.id.selectedSkill);
        textView.setText("点击武将名字进行选择");

        confirmButton.setOnClickListener(v -> handleConfirmButtonClick(xinsheng, replace, buttonContainer, textView));

        return confirmButton;
    }

    private void handleConfirmButtonClick(Button xinsheng, Button replace, LinearLayout buttonContainer, TextView textView) {
        if (selectedLinearLayoutCount != 0) {
            handleSelectedLinearLayouts();
            which += 2;
            which %= getZCData().size();
            if (selectedLinearLayoutCount == 2) {
                xinsheng.performClick();
            }
            xinsheng.performClick();
            resetSelectionState(xinsheng, replace, buttonContainer, textView);
        } else {
            Toast.makeText(this, "请选择武将!!", Toast.LENGTH_SHORT).show();
        }
    }

    private void handleSelectedLinearLayouts() {
        List<LinearLayout> toRemove = new ArrayList<>();
        for (LinearLayout ll : linearLayoutList) {
            if (ll.isSelected()) {
                toRemove.add(ll);
            }
        }

        for (LinearLayout ll : toRemove) {
            updateZCDataSelectionStatus(ll);
            removeLinearLayout(ll);
        }
    }

    private void updateZCDataSelectionStatus(LinearLayout ll) {
        for (ZCData zcData : getZCData()) {
            if (zcData.name.equals(((TextView) ll.getChildAt(0)).getText().toString())) {
                zcData.is_selected = false;
                break;
            }
        }
    }

    private void resetSelectionState(Button xinsheng, Button replace, LinearLayout buttonContainer, TextView textView) {
        selectedLinearLayoutCount = 0;
        isReplaceEnabled = false;
        xinsheng.setVisibility(View.VISIBLE);
        replace.setVisibility(View.VISIBLE);
        if (confirmButton != null) { // 检查 confirmButton 是否为空
            buttonContainer.removeView(confirmButton); // 使用成员变量来移除确认按钮
        }
        textView.setText("");
    }

    private void simulateButtonClick(Button button) {
        if (button != null) {
            button.performClick();
        }
    }

    public void createLinearlayout(ZCData zcData, LinearLayout topContainer) {
        LinearLayout dynamicLinearLayout = createLinearLayout();
        TextView dynamicTextView = createTextView(zcData.name);
        dynamicLinearLayout.addView(dynamicTextView);

        addSkillButtons(zcData, dynamicLinearLayout);

        topContainer.addView(dynamicLinearLayout);
        linearLayoutList.add(dynamicLinearLayout); // 将创建的 LinearLayout 添加到 linearLayoutList 中
    }

    private LinearLayout createLinearLayout() {
        LinearLayout dynamicLinearLayout = new LinearLayout(this);
        dynamicLinearLayout.setId(View.generateViewId());
        dynamicLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
        dynamicLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        ));

        dynamicLinearLayout.setOnClickListener(v -> handleLinearLayoutClick(dynamicLinearLayout));

        return dynamicLinearLayout;
    }

    private TextView createTextView(String text) {
        TextView dynamicTextView = new TextView(this);
        dynamicTextView.setText(text);
        dynamicTextView.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        ));
        dynamicTextView.setTextSize(20);
        dynamicTextView.setGravity(Gravity.CENTER_VERTICAL);
        dynamicTextView.setTextColor(ContextCompat.getColor(this, R.color.blue));
        dynamicTextView.setTypeface(dynamicTextView.getTypeface(), Typeface.BOLD);
        dynamicTextView.setPadding(0, 0, 0, 16); // 设置底部间距

        return dynamicTextView;
    }

    private void addSkillButtons(ZCData zcData, LinearLayout dynamicLinearLayout) {
        addSkillButton(zcData.s_name_1, zcData.skill_1, dynamicLinearLayout);
        addSkillButton(zcData.s_name_2, zcData.skill_2, dynamicLinearLayout);
        addSkillButton(zcData.s_name_3, zcData.skill_3, dynamicLinearLayout);
    }

    private void addSkillButton(String skillName, String skillDescription, LinearLayout dynamicLinearLayout) {
        if (skillName != null && !skillName.isEmpty()) {
            Button button = createSkillButton(skillName, skillDescription);
            TextViewButtonPair pair = new TextViewButtonPair(button);
            buttonsList.add(pair);
            dynamicLinearLayout.addView(button);
        }
    }

    private Button createSkillButton(String skillName, String skillDescription) {
        Button dynamicButton = new Button(this);
        dynamicButton.setText(skillName);
        dynamicButton.setBackgroundResource(R.drawable.zc_button);
        dynamicButton.setTextColor(ContextCompat.getColor(this, R.color.black));
        dynamicButton.setTextSize(18);
        dynamicButton.setTypeface(null, Typeface.BOLD);

        dynamicButton.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        ));

        int buttonIndex = buttonsList.size(); // 获取当前按钮的索引
        dynamicButton.setTag(buttonIndex);

        dynamicButton.setOnClickListener(v -> handleSkillButtonClick(v, skillDescription));

        return dynamicButton;
    }

    private void handleSkillButtonClick(View v, String skillDescription) {
        int buttonIndex = (int) v.getTag(); // 获取按钮的索引
        Button clickedButton = (Button) v;

        // 取消其他按钮的选中状态
        for (TextViewButtonPair pair : buttonsList) {
            if (pair.getButton() == clickedButton) {
                pair.setSelected(true);
                clickedButton.setBackgroundResource(R.drawable.red_button);
            } else {
                pair.setSelected(false);
                pair.getButton().setBackgroundResource(R.drawable.zc_button);
            }
        }

        showSkill.setText(skillDescription);
    }

    public List<ZCData> getZCData() {
        List<ZCData> list = new ArrayList<>();
        Cursor cursor = myDatabase.rawQuery("SELECT * FROM zuoci", null);
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst(); // 将 cursor 移动到第一个光标上
            int count = cursor.getCount();

            // 获取列索引
            int nameIndex = cursor.getColumnIndex("name");
            int sName1Index = cursor.getColumnIndex("s_name_1");
            int sName2Index = cursor.getColumnIndex("s_name_2");
            int sName3Index = cursor.getColumnIndex("s_name_3");
            int skill1Index = cursor.getColumnIndex("skill_1");
            int skill2Index = cursor.getColumnIndex("skill_2");
            int skill3Index = cursor.getColumnIndex("skill_3");
            int isSelectedIndex = cursor.getColumnIndex("isSelected");

            // 检查所有列索引是否有效
            if (areColumnIndicesValid(nameIndex, sName1Index, sName2Index, sName3Index, skill1Index, skill2Index, skill3Index, isSelectedIndex)) {
                for (int i = 0; i < count; i++) {
                    cursor.moveToPosition(i);
                    ZCData zcdata = new ZCData();
                    zcdata.name = cursor.getString(nameIndex);
                    zcdata.s_name_1 = cursor.getString(sName1Index);
                    zcdata.s_name_2 = cursor.getString(sName2Index);
                    zcdata.s_name_3 = cursor.getString(sName3Index);
                    zcdata.skill_1 = cursor.getString(skill1Index);
                    zcdata.skill_2 = cursor.getString(skill2Index);
                    zcdata.skill_3 = cursor.getString(skill3Index);
                    zcdata.is_selected = cursor.getInt(isSelectedIndex) == 1;
                    list.add(zcdata);
                }
            } else {
                Log.e(TAG, "One or more column names do not exist in the database table.");
            }
        }
        if (cursor != null) {
            cursor.close();
        }
        return list;
    }

    private boolean areColumnIndicesValid(int... indices) {
        for (int index : indices) {
            if (index == -1) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myDatabase != null) {
            myDatabase.close();
        }
    }

    // 新增方法：删除指定的 LinearLayout
    public void removeLinearLayout(LinearLayout linearLayoutToRemove) {
        if (linearLayoutList.contains(linearLayoutToRemove)) {
            linearLayoutList.remove(linearLayoutToRemove);

            View parent = (View) linearLayoutToRemove.getParent();
            if (parent instanceof ViewGroup) {
                ((ViewGroup) parent).removeView(linearLayoutToRemove);
            }
        } else {
            Log.d(TAG, "LinearLayout not found in the list.");
        }
    }

    private void handleLinearLayoutClick(LinearLayout dynamicLinearLayout) {
        if (isReplaceEnabled) {
            toggleLinearLayoutSelection(dynamicLinearLayout);
        }
    }

    private void toggleLinearLayoutSelection(LinearLayout dynamicLinearLayout) {
        if (dynamicLinearLayout.isSelected()) {
            deselectLinearLayout(dynamicLinearLayout);
        } else if (selectedLinearLayoutCount < 2) {
            selectLinearLayout(dynamicLinearLayout);
        } else {
            Toast.makeText(this, "最多只能选择两个", Toast.LENGTH_SHORT).show();
        }
    }

    private void deselectLinearLayout(LinearLayout dynamicLinearLayout) {
        dynamicLinearLayout.setSelected(false);
        dynamicLinearLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.tt));
        selectedLinearLayoutCount--;
    }

    private void selectLinearLayout(LinearLayout dynamicLinearLayout) {
        dynamicLinearLayout.setSelected(true);
        dynamicLinearLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.green));
        selectedLinearLayoutCount++;
    }
}
